package com.dm.dao.impl;

import com.dm.dao.BaseDao;
import com.dm.dao.RecordDao;
import com.dm.dto.RecordDto;
import com.dm.entity.Record;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author hqw521@qq.com
 * @date 2018/11/16 13:33
 */
@Repository
public class RecordDaoImpl implements RecordDao {
    @Autowired
    private BaseDao baseDao;

    @Override
    public Integer insertRecord(Record record) {
        String sql = "insert into dm_record (user_id, operation) values (?, ?)";
        Query query = baseDao.getSession().createSQLQuery(sql);
        query.setInteger(0, record.getUserId());
        query.setString(1, record.getOperation());
        return query.executeUpdate();
    }

    @Override
    public List<RecordDto> findRecords(Integer page, Integer pageSize) {
        String sql = "SELECT\n" +
                "\tdu.user_name userName,\n" +
                "\tdr.create_time time,\n" +
                "\tdr.operation operation\n" +
                "FROM\n" +
                "\tdm_record dr\n" +
                "LEFT JOIN dm_user du ON du.user_id = dr.user_id\n" +
                "ORDER BY\n" +
                "\tdr.create_time DESC\n" +
                "LIMIT ?, ?";
        Query query = this.baseDao.getSession().createSQLQuery(sql).setResultTransformer(Transformers.aliasToBean(RecordDto.class));
        query.setInteger(0, page);
        query.setInteger(1, pageSize);

        List<RecordDto> recordDtos = query.list();
        return recordDtos;
    }

    @Override
    public Long selectCount() {
        String hql = "select count(1) from Record";
        Query query = baseDao.getSession().createQuery(hql);
        return (Long) query.iterate().next();
    }
}
